<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action=""
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="handleAvatarSuccess"
    >
      <img v-if="img" :src="img" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <!-- 生成button按钮 -->
      <el-button size="small" type="primary">上传头像</el-button>

    </el-upload>
    <el-progress :percentage="percentage" />
    <el-progress type="circle" :percentage="percentage" />
  </div>
</template>

<script>
// sdk  software develop kit  软件开发工具集
// 这个js文件，就是给我们提供很多操作这个云储存的一些 js方法
import COS from 'cos-js-sdk-v5'

// 初始化COS储存桶， 使用id和key
const cos = new COS({
  SecretId: 'AKIDXzGJApFSRCdokcLr77tSm8JQP8bYFiyz',
  SecretKey: 'yjDSRAdzT3b2HI8sQlslPp3D8d6OexFc'
})

export default {
  name: 'ImageUpload',
  props: {
    img: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      percentage: 0
    }
  },
  methods: {
    handleAvatarSuccess(e) {
      const that = this
      cos.putObject(
        {
          Bucket: 'heima92-1305752761' /* 填入您自己的存储桶，必须字段 */,
          Region: 'ap-nanjing' /* 存储桶所在地域，例如ap-beijing，必须字段 */,
          Key: e.file
            .name /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
          Body: e.file /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */,
          onProgress: function(progressData) {
            that.percentage = progressData.percent * 100
          }
          // eslint-disable-next-line handle-callback-err
        },
        function(_err, data) {
          if (data.statusCode === 200 && data.Location) {
            that.$emit('update:img', `http://${data.Location}`)
          }
        }
      )
    },
    // 这个beforeAvatarUpload 什么意思，返回true和false表示什么

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!')
      // }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!')
      // }
      // return isJPG && isLt2M
      return true
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

</style>

<style lang="scss" scoped></style>
